package com.jinyou.chengfengshop.activity;

import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.Constant.Config;
import com.jinyou.chengfengshop.OkHttpUtils.CallBackUtil;
import com.jinyou.chengfengshop.OkHttpUtils.OkhttpUtil;
import com.jinyou.chengfengshop.R;
import com.jinyou.chengfengshop.bean.RechareBean;
import com.jinyou.chengfengshop.payUtils.WXPayUtil;
import com.jinyou.chengfengshop.utils.CommonEvent;
import com.jinyou.chengfengshop.utils.CommonEventKey;
import com.jinyou.chengfengshop.wxapi.WXPayEntryActivity;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 *
 * 充值订单提交
 * Created by zhuzhiqiang on 2018/9/26.
 */

public class SubmitRechargeActivity extends AppCompatActivity {
    private TextView orderId_tv;
    private TextView orderMoney_tv;
    private TextView pay_tv;
    private TextView back_tv;

    private String recInfo;
    private String tocken;
    private String ordernum;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_recharge);

        EventBus.getDefault().register(this);

        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        tocken = sh.getString("tocken","");

        orderId_tv = (TextView) findViewById(R.id.orderId_tv);
        orderMoney_tv = (TextView) findViewById(R.id.orderMoney_tv);
        pay_tv = (TextView) findViewById(R.id.pay_tv);
        pay_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRechargeSign(ordernum);

            }
        });
        recInfo = getIntent().getStringExtra("recinfo");
        try {
            JSONObject ob = new JSONObject(recInfo);
            orderId_tv.setText("订单号: "+ob.getString("orderNo"));
            orderMoney_tv.setText("¥ "+ob.getString("consumeMoneyRmb"));
            ordernum = ob.getString("orderNo");

        } catch (JSONException e) {
            e.printStackTrace();
        }

        back_tv = (TextView) findViewById(R.id.back_tv);
        back_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    //获取充值sign
    private void getRechargeSign(String orderid){
        //RECHARGE_SIGN
        HashMap<String,String> paramsMap = new HashMap<>();
        paramsMap.put("token",tocken);
        paramsMap.put("sysCustomer","o2o-chengfeng");
        paramsMap.put("orderNo",orderid);
        paramsMap.put("payType","wx");


        OkhttpUtil.okHttpPost(AppUrl.RECHARGE_SIGN, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {
                Toast.makeText(SubmitRechargeActivity.this,"失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {

                    JSONObject obj = new JSONObject(response);

                            WXPayUtil.pay(getApplicationContext(), obj.getString("appid"),
                                    obj.getString("partnerid"), obj.getString("prepayid"), obj.getString("package"),
                                    obj.getString("noncestr"), obj.getString("timestamp"), obj.getString("sign"));


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });



    }


    @Override
    protected void onResume() {
        super.onResume();
    }



    //服务器回调
    protected void getOrderPayCallBack() {

            HashMap<String,String> paramsMap = new HashMap<>();
            paramsMap.put("token",tocken);
            paramsMap.put("sysCustomer","o2o-chengfeng");
            paramsMap.put("orderNo",ordernum);
            paramsMap.put("payType","wx");

            OkhttpUtil.okHttpPost(AppUrl.RECHARGE_CALLBACK, paramsMap, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Toast.makeText(SubmitRechargeActivity.this,"失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response) {//请求成功时调用，执行在UI线程
                    try {

                        JSONObject obj = new JSONObject(response);
                        int code = obj.getInt("status");
                        if(code == 1){
                            Toast.makeText(SubmitRechargeActivity.this,"充值到账～",Toast.LENGTH_SHORT).show();
                            finish();
                        }else {
                            Toast.makeText(SubmitRechargeActivity.this,obj.getString("error"),Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });


//        deliver/recharge/shop/order/pay/notify
//        if (TextUtils.isEmpty(ordernum)) {
//            return;
//        }
//        StartActions.getOrderPayCallBack(channelType, orderNo, tradeNo, new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//                PaymentActivity.this.finish();
//                EventBus.getDefault().post(new CommonEvent(CommonEventKey.PAY_CALLBACK_SUCCESS));//订单回调成功，刷新订单列表
//            }
//
//            @Override
//            public void onFailure(HttpException e, String s) {
//
//            }
//        });
    }


    //@Subscribe

    public void onEventMainThread(CommonEvent event) {
        switch (event.getKey()) {
            case CommonEventKey.PAY_SUCCESS: {//支付成功
                getOrderPayCallBack();
                Log.i("onEventMainThread","----------------支付成功");
                //Toast.makeText(getApplicationContext(),"mmmmmmmmm",Toast.LENGTH_SHORT).show();
            }
            break;
            case CommonEventKey.PAY_FAIL: {//支付失败
                Toast.makeText(getApplicationContext(),"nnnnnnnnn",Toast.LENGTH_SHORT).show();
                //Log.i("onEventMainThread","----------------支付失败");
            }
            break;
            case CommonEventKey.PAY_CANCEL: {//支付取消
                //Toast.makeText(getApplicationContext(),"bbbbbbbbb",Toast.LENGTH_SHORT).show();
                Log.i("onEventMainThread","----------------支付取消");
            }
            break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
